<template>
  <a-drawer width="35%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules">
      <!-- Contract Name -->
      <a-form-model-item label="合同名称" prop="name">
        <a-input v-model="form.name" placeholder="请输入合同名称" />
      </a-form-model-item>
      <!-- Start Date -->
      <a-form-model-item label="合同开始日期" prop="contractStartDate">
        <a-date-picker v-model="form.contractStartDate"
                       @change="onStartDateChange"

                       style="width: 100%" placeholder="请选择开始日期" />
      </a-form-model-item>
      <!-- End Date -->
      <a-form-model-item label="合同结束日期" prop="contractEndDate">
        <a-date-picker v-model="form.contractEndDate"
                       :disabledDate="disabledEndDate"
                       style="width: 100%" placeholder="请选择结束日期" />
      </a-form-model-item>
      <!-- Status -->
      <a-form-model-item label="合同类型" prop="type">
        <a-select placeholder="请选择合同类型" v-model="form.type">
          <a-select-option v-for="(d, index) in statusOptions" :key="index" :value="d.value">{{ d.label }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="文件" prop="filePath">
        <a-upload
          accept=".pdf"
          :headers="headers"
          :file-list="fileList"
          :action="uploadImgUrl"
          :before-upload="beforeUpload"
          :remove="handleRemove"
          listType="text"
        >
          <a-button icon="upload">点击上传文件</a-button>
        </a-upload>

        <!-- File Preview if filePath is available -->
        <div v-if="form.filePath">
          <a href="javascript:void(0);" @click="previewFile">
            <a-icon type="file" />
            预览文件
          </a>
        </div>
      </a-form-model-item>
      <!-- Remarks -->
      <a-form-model-item label="员工（请选择到具体的员工）" prop="staffId">
        <!--        <dept-tree-->
        <!--          ref="deptTree"-->
        <!--          :deptOptions="staffOptions"-->
        <!--          @change="clickStaffNode"-->
        <!--        />-->

        <a-tree-select
          :tree-data="staffOptions"
          :replaceFields="replaceFields"
          :checkable="true"
          :defaultExpandAll="true"
          @select="clickStaffNode"
          :fieldNames="fieldNames"
          placeholder="请选择员工"
          :showSearch="true"
          v-model="form.staffId"
          :filterTreeNode="filterStaffNode"
          searchPlaceholder="请输入员工姓名"
        >
        </a-tree-select>
      </a-form-model-item>
      <a-form-model-item label="备注" prop="remark">
        <a-input v-model="form.remark" placeholder="请输入备注" type="textarea" allow-clear />
      </a-form-model-item>
      <!-- Control Buttons -->
      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="addAndUploadContract">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>

import { getContract, addContract, updateContract, uploadContract } from '@/api/system/contract'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import DeptTree from '@/views/system/user/modules/DeptTree.vue'
import { staffTreeSelect } from '@/api/system/user'

export default {
  name: 'CreateForm',
  components: { DeptTree },
  props: {
    statusOptions: {
      type: Array,
      required: true
    },
    staffOptions: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      // 自定义字段名
      fieldNames: {
        title: 'label', // 显示的名称
        key: 'id', // 节点的唯一标识
        children: 'children', // 子节点
        selectable: 'selectable', // 是否可选
        checkable: 'checkable' // 是否显示单选框
      },
      replaceFields: { children: 'children', title: 'label', key: 'id', value: 'id' },

      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      submitLoading: false,
      formTitle: '',
      // Form parameters for contract
      form: {
        contractId: undefined,
        name: undefined,
        contractCode: undefined,
        contractStartDate: null,
        contractEndDate: null,
        type: '0',
        remark: undefined,
        filePath: '',
        staffId: ''
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      open: false,
      fileList: [],
      rules: {
        name: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '合同类型不能为空', trigger: 'blur' }],
        staffId: [{ required: true, message: '请选择员工', trigger: 'change' }],

        contractStartDate: [{ required: true, message: '合同开始日期不能为空', trigger: 'change' }],
        contractEndDate: [{ required: true, message: '合同结束日期不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    // 处理后的树数据，动态设置每个节点的 checkable 和 selectable 属性

  },
  methods: {
    // 更新结束日期选择器的可选日期
    onStartDateChange(date) {
      this.form.contractEndDate = null // 清空结束日期
    },
    // 禁用开始日期之前的日期
    disabledEndDate(current) {
      return current && current < this.form.contractStartDate // 禁用小于开始日期的日期
    },
    filterStaffNode(inputValue, treeNode) {
      let tempNode = treeNode.data.props.dataRef
      return this.recursiveSearch(tempNode, inputValue)
    },

    recursiveSearch(node, inputValue) {
      // 如果节点是员工 (type === 'staff') 且 label 包含输入的搜索关键字，返回 true
      if (node.type === 'staff' && node.label.includes(inputValue)) {
        return true
      }

      // 如果有子节点，递归地检查每个子节点
      if (node.children && node.children.length > 0) {
        return node.children.some((child) => this.recursiveSearch(child, inputValue))
      }
      return false
    },
    // 处理节点点击事件
    clickStaffNode(selectedKeys, { node }) {
      this.form.staffId = selectedKeys
    },
    onClose() {
      this.open = false
    },
    cancel() {
      this.open = false
      this.reset()
    },
    // Reset form fields
    reset() {
      this.form = {
        contractId: undefined,
        name: undefined,
        contractCode: undefined,
        contractStartDate: null,
        contractEndDate: null,
        staffId: null,
        status: '0',
        remark: undefined,
        staff: null
      }
    },
    /** Add Contract */
    handleAdd() {
      this.reset()
      this.open = true
      this.formTitle = '添加合同'
    },
    // clickStaffNode(staff) {
    //   this.form.staff = staff
    //   console.log(staff)
    //   if (staff && staff.type==='staff' ) {
    //    this.form.staffId = staff.id
    //   }
    // },
    /** Update Contract */
    handleUpdate(row, ids) {
      this.reset()
      const contractId = row ? row.contractId : ids
      getContract(contractId).then(response => {
        this.form = response.data
        this.open = true
        this.formTitle = '修改合同'
      })
    },
    /** Submit the form */
    submitForm() {

      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.contractId !== undefined) {
            updateContract(this.form).then(response => {
              this.$message.success('修改成功', 3)
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            addContract(this.form).then(response => {
              this.$message.success('新增成功', 3)
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    handleRemove() {
      this.fileList = []
      this.uploading = false
    },
    addAndUploadContract() {
      const { fileList } = this
      const formData = new FormData()
      formData.append('file', fileList[0])
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!fileList || fileList.length < 1) {
            this.submitForm()
          } else {
            uploadContract(formData).then(response => {
              console.log('上传合同成功', response)
              this.fileList = []
              this.form.filePath = response.url
              this.$message.success(response.msg)
              this.submitForm()

            }).finally((error) => {
              console.log('上传合同出错了', error)
            })
          }
        } else {
          return false
        }
      })

    },
    handleFileChange(info) {

      if (info.file.status === 'done' || info.file.status === 'uploading') {
        this.fileList = info.file.fileList
        // this.form.filePath = info.file.url
      } else if (info.file.status === 'error') {
        this.$message.error('文件上传失败')
      }
    },
    // TODO File preview (Open the file in a new window)
    previewFile() {
      window.open(this.form.filePath, '_blank')
    },
    beforeUpload(file) {
      const isValidType = file.type === 'application/pdf' // Example: Only allow PDF files
      if (!isValidType) {
        this.$message.error('只能上传PDF文件')
      }
      this.fileList = [file]
      return isValidType
    }
  }
}
</script>
